package tc.crase.view;

import java.util.Vector;

import tc.common.registry.Filter;
import tc.common.registry.Obj;
import tc.common.registry.Ref;
import tc.common.registry.RegistrySys;
import tc.common.registry.Rview;
import tc.crase.db.Xobject;
import tc.crase.sys.XdbRoot;
import tc.crase.sys.XobjectEx;


public class Refs {
	Rview view;
	Filter filter;
	public Vector<Ref> refs = new Vector<Ref>();
	
	public Refs(Rview view, Filter filter) {
		this.view = view;
		this.filter = filter;
		
		/*for (Xobject object: XdbRoot.xdbsys.current) {
			 
			XobjectEx objectEx = (XobjectEx)object;
			if (filter.pass(objectEx.objex) == false) continue;
			refs.add(new Ref(objectEx.objex, view));
		}*/
		
		for (Obj obj : RegistrySys.registry.objects.values()) {
			if (obj instanceof XobjectEx.ObjEx == false) continue;
			if (filter.pass(obj) == false) continue;
			refs.add(new Ref(obj, view));
		}
	}
	
	private Ref getRef(Obj obj) {
		for (Ref ref : refs) {
			if (ref.original == obj) return ref;
		}
		
		return null;
	}
	
	public void onRefChanged(Ref ref) {
		if (ref.original.state == Obj.State.CHANGED) {
			view.setDirty(true);
		} else if (ref.original.state == Obj.State.DELETED) {
			refs.remove(ref);
		}
	}
	
	public void checkPresence() {
		for (int i = 0; i < RegistrySys.registry.changed.size(); i++) {
			Obj obj = RegistrySys.registry.changed.get(i);
			if (obj instanceof XobjectEx.ObjEx == false)
				continue;
			XobjectEx.ObjEx xobj = (XobjectEx.ObjEx)obj;
			
			Ref present = null;
			if (obj.state != Obj.State.NEW) present = getRef(obj);
			
			if (filter.pass(xobj)) {
				if (present != null) continue;
				refs.add(new Ref(xobj, view));
				view.setDirty(true);
			}
			else {
				if (present == null) continue;
				refs.remove(present);
				view.setDirty(true);
			}
		}
	}
}
